<template>
	<div>
		<div class="crumbs">
			<el-breadcrumb separator="/">
				<el-breadcrumb-item>
					<i class="el-icon-lx-cascades"></i> 帖子管理
				</el-breadcrumb-item>
			</el-breadcrumb>
		</div>
		<div class="container">
			<div class="handle-box">
				<el-button type="primary" icon="el-icon-delete" class="handle-del mr10" @click="delAllSelection">批量删除</el-button>
				  
				<el-input v-model="query.title" placeholder="标题" class="handle-input mr10"></el-input>
				<el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
				<el-button type="danger" icon="el-icon-plus" @click="handleAdd">添加</el-button>
			</div>
			<el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header"
			 @selection-change="handleSelectionChange" style="min-height:400px">
				<el-table-column type="selection" width="55" align="center"></el-table-column>
				<el-table-column prop="id" label="ID" width="120" align="center"></el-table-column>
				<el-table-column prop="menuName" label="所属菜单" width="120" align="center"></el-table-column>
				<el-table-column prop="title" label="标题" width="260"></el-table-column>
				<el-table-column prop="secondTitle" label="副标题" width="260"></el-table-column>
				<el-table-column prop="author" label="作者" align="center"></el-table-column>
				<el-table-column prop="digest" label="摘要" width="210" show-overflow-tooltip></el-table-column>
				<el-table-column prop="content" label="内容" width="360" show-overflow-tooltip></el-table-column>
				<el-table-column prop="createTime" width="210" label="创建时间" :formatter="dateFormat"></el-table-column>
				<el-table-column prop="updateTime" width="210" label="修改时间" :formatter="dateFormat"></el-table-column>
				<el-table-column prop="hittimes" label="浏览量"></el-table-column>
				<el-table-column label="状态" align="center">
					<template slot-scope="scope">
						<el-tag :type="scope.row.state=='1'?'success':(scope.row.state=='0'?'danger':'')">{{scope.row.state=='1'?'正常':'禁用'}}</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="180" align="center">
					<template slot-scope="scope">
						<el-button type="text" icon="el-icon-view" @click="handlePreview(scope.$index, scope.row)">
							<font color="#67C23A">预览</font>
						</el-button>
						<el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
						<el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div class="pagination">
				<el-pagination background layout="total, sizes, prev, pager, next, jumper" :current-page="query.pageIndex"
				 :page-size="query.pageSize" :total="recordTotal" @current-change="handlePageChange" @size-change="handleSizeChange"></el-pagination>
			</div>
		</div>


		<!-- 添加弹出框 -->
		<el-dialog title="添加" :visible.sync="addVisible" width="60%">
			<el-row :gutter="15">
				<el-form ref="elForm" :model="form" :rules="rules" size="medium" label-width="100px">
					<el-col :span="12">
						<el-form-item label="文章类别" prop="menuId">
							<!-- <el-select clearable v-model="form.menuId" placeholder="请选择">
								<el-option v-for="item in menuList" :key="item.menuId" :label="item.menuName" :value="item.menuId">
									<span style="float: left">{{ item.menuName }}</span>
								</el-option>
							</el-select> -->
							<el-tree
							      :data="menuTree"
							      show-checkbox
							      accordion
							      :check-strictly="true"
							      :default-expand-all="false"
							      node-key="menuId"
							      ref="tree"
							      highlight-current
							    >
							      <span class="custom-tree-node" slot-scope="{ data }">
							        <span>{{ data.menuName }}</span>
							        <span> </span>
							      </span>
							    </el-tree>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="标题" prop="title">
							<el-input v-model="form.title" placeholder="请输入标题" clearable :style="{width: '100%'}">
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="作者" prop="author">
							<el-input v-model="form.author" placeholder="请输入作者" clearable :style="{width: '100%'}">
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="副标题" prop="secondTitle">
							<el-input v-model="form.secondTitle" placeholder="请输入副标题" clearable :style="{width: '100%'}"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="摘要" prop="digest">
							<el-input v-model="form.digest" placeholder="请输入摘要" clearable :style="{width: '100%'}">
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="状态" prop="state">
							<el-switch v-model="form.state"  :active-value='1'
							 :inactive-value='0'></el-switch>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="内容">
							<quill-editor ref="myTextEditor" v-model="form.content" :height="300"></quill-editor>
						</el-form-item>
					</el-col>
				</el-form>
			</el-row>
			<div slot="footer">
				<el-button @click="closeDialog">取 消</el-button>
				<el-button type="primary" @click="saveAdd">提 交</el-button>
				<el-button @click="resetForm">重置</el-button>
			</div>
		</el-dialog>

		<!-- 编辑弹出框 -->
		<el-dialog title="编辑" :visible.sync="editVisible" width="60%">
			<el-row :gutter="15">
				<el-form ref="elForm" :model="form" :rules="rules" size="medium" label-width="100px">
					<el-col :span="12">
						<el-form-item label="文章类别" prop="menuId">
							<!-- <el-select clearable v-model="form.menuId" placeholder="请选择">
								<el-option v-for="item in menuList" :key="item.menuId" :label="item.menuName" :value="item.menuId">
									<span style="float: left">{{ item.menuName }}</span>
								</el-option>
							</el-select> -->
							<el-tree
							      :data="menuTree"
							      show-checkbox
							      accordion
							      :check-strictly="true"
							      :default-expand-all="false"
							      node-key="menuId"
							      ref="tree"
							      highlight-current
							    >
							      <span class="custom-tree-node" slot-scope="{ data }">
							        <span>{{ data.menuName }}</span>
							        <span> </span>
							      </span>
							    </el-tree>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="标题" prop="title">
							<el-input v-model="form.title" placeholder="请输入标题" clearable :style="{width: '100%'}">
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="作者">
							<el-input v-model="form.author" placeholder="请输入作者" clearable :style="{width: '100%'}">
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="副标题" prop="secondTitle">
							<el-input v-model="form.secondTitle" placeholder="请输入副标题" clearable :style="{width: '100%'}"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="摘要">
							<el-input v-model="form.digest" placeholder="请输入摘要" clearable :style="{width: '100%'}">
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="状态" prop="state">
							<el-switch v-model="form.state" :active-value='1'
							 :inactive-value='0'></el-switch>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="内容">
							<quill-editor ref="myTextEditor" v-model="form.content" :height="300"></quill-editor>
						</el-form-item>
					</el-col>
				</el-form>
			</el-row>
			<div slot="footer">
				<el-button @click="closeDialog">取 消</el-button>
				<el-button type="primary" @click="saveEdit">提 交</el-button>
				<el-button @click="resetForm">重置</el-button>
			</div>
		</el-dialog>

		<!-- 预览弹出框 -->
		<!-- <el-dialog title="预览" :visible.sync="previewVisible" width="60%">
			<el-row >
				 <el-col :span="12" :offset="6">
					<table style="border:1px black solid;width: 100%;text-align:center;">
						<tr>
							<td>标题</td>
							<td v-text="form.title"></td>
						</tr>
						<tr>
							<td>作者</td>
							<td v-text="form.author"></td>
						</tr>
						<tr>
							<td>副标题</td>
							<td v-text="form.secondTitle"></td>
						</tr>
						<tr>
							<td>标题</td>
							<td v-text="form.title"></td>
						</tr>
						<tr>
							<td>摘要</td>
							<td v-text="form.digest"></td>
						</tr>
						<tr>
							<td>状态</td>
							<td v-text="form.state"></td>
						</tr>
						<tr>
							<td>内容</td>
							<td v-text="form.content"></td>
						</tr>
					</table>
				 </el-col>
			</el-row> -->

		<!-- <el-row :gutter="15">
				 <el-col :span="6" :offset="6">
					 标题：
				 </el-col>
				 <el-col :span="12">
				 	<div v-text="form.title"></div>
				 </el-col>
			</el-row> -->
		<div slot="footer">
			<el-button @click="previewVisible=false">取 消</el-button>
		</div>
		</el-dialog>

	</div>
</template>

<script>
	/* import { fetchData } from '../../index'; */
	import axios from 'axios';
	import moment from 'moment';

	import {
		quillEditor
	} from 'vue-quill-editor';
	import 'quill/dist/quill.core.css';
	import 'quill/dist/quill.snow.css';
	import 'quill/dist/quill.bubble.css';

	export default {
		name: 'basetable',
		data() {
			return {
				// 控制新增编辑弹窗的显示与隐藏
				addOrUpdateVisible: false,
				query: {
					title: '',
					pageIndex: 1, //分页页面索引
					pageSize: 10 //每页面显示的记录数,默认显示10条
				},
				tableData: [],
				menuList: [],
				menuTree: [],
				multipleSelection: [],
				delList: [],
				addVisible: false,
				editVisible: false,
				previewVisible: false,
				pageTotal: 0,
				recordTotal: 0,
				form: {
					menuId: '',
					title: undefined,
					author: undefined,
					secondTitle: undefined,
					digest: undefined,
					state: 1,
					content: "",
				},
				articleData: {},
				idx: -1,
				id: -1,
				instance: null, //请求实例对象
				searchVisiable: false, //搜索状态
				rules: {
					// menuId: [{
					// 	required: true,
					// 	message: '请输入菜单类型',
					// 	trigger: 'blur'
					// }],
					title: [{
						required: true,
						message: '请输入标题',
						trigger: 'blur'
					}],
				},
			};
		},
		created() {
			this.getUserData(this.query.pageIndex, this.query.pageSize);
			this.getBoardList();
		},
		components: {
			quillEditor
		},
		methods: {
			//获取节点树
			    getBoardList() {
				let that = this;
				 //搜索并请求分页数据
				 axios.get('/api/menu/boardList', {
				 	
				 }).then(res => { //请求成功，返回数据
				 	that.menuTree = res.data.data.boardList;
					console.log("menuTree:"+that.menuTree);
					console.log("res.data.boardList:",res.data.data.boardList);
				 
				 }).catch(err => { //错误处理
				 	console.log(err)
				 })
			      
			    },
			
			    //检查树状结构结构
			    getCheckedNodes() {
			      var getlist = this.$refs.tree
			        .getCheckedNodes()
			        .concat(this.$refs.tree.getHalfCheckedNodes());
			      // 循环遍历当前节点的值
			      for (var i in getlist) {
			        // 判断子节点是否存在子节点 如果存在直接请求并且提示 false
			        if (!getlist[i].hasOwnProperty("children")) {
			          // 判断是否只选择一个 如果存在直接请求并且提示 false
			          if (getlist.length == 1) {
					  this.form.menuId=getlist[0].menuId;
					  console.log("this.form.menuId1:"+this.form.menuId);
			          } else {
			            this.$message.error("只选择一个节点");
			            this.$refs.tree.setCheckedKeys([]);
			            return;
			          }
			        } else if(getlist.length>1){
			              this.$message.error("只能选择一个子节点");
			              this.$refs.tree.setCheckedKeys([]);
			              return;
			        }else{
					   this.form.menuId=getlist[0].menuId;
			            console.log("this.form.menuId2"+this.form.menuId);
			        }
			      }
			    },
			    resetChecked() {
			      this.$refs.tree.setCheckedKeys([]);
			    },
			
			//关闭对话框
			closeDialog() {
				this.$refs['elForm'].resetFields();
				this.form = {
					id: '',
					menuId: 0,
					title: undefined,
					author: undefined,
					secondTitle: undefined,
					digest: undefined,
					state: 1,
					content: "",
				}
				this.addVisible = false;
				this.editVisible = false;
			},
			resetForm() {
				this.$refs['elForm'].resetFields()
			},

			//定义拦截器方法
			interceptor() {
				console.log('请求拦截器调用')
				// 添加请求拦截器，在请求头中加token
				axios.interceptors.request.use(
					config => { //请求成功时，对请求作拦截处理
						if (localStorage.getItem('Authorization')) {
							config.headers.Authorization = localStorage.getItem('Authorization');
						} else {
							console.log('读取token失败')
						}
						return config;
					},
					error => { //请求失败时
						return Promise.reject(error);
					});
			},

			getUserData(pageIndex, pageSize) {
				axios.get('/api/article/page', {
					params: {
						pages: pageIndex,
						size: pageSize
					}
				}).then(res => { //请求成功，返回数据
					this.tableData = res.data.data.list; //绑定数据到模型数据
					this.pageTotal = res.data.data.pageTotal;
					this.recordTotal = res.data.data.recordTotal;
					this.menuList = res.data.data.menuList;
				}).catch(err => { //错误处理
					console.log(err)
				})
			},

			// 触发搜索按钮
			handleSearch() {
				//修改搜索状态，在分页时将调用搜索列表方法
				this.searchVisiable = true;
				//搜索第1页
				this.searchListPages(1);
			},
			searchListPages(val) {
				//搜索并请求分页数据
				axios.get('/api/article/search', {
					params: {
						pages: val,
						size: this.query.pageSize,
						title: this.query.title
					}
				}).then(res => { //请求成功，返回数据
					console.log(res)
					this.tableData = res.data.data.list; //绑定数据到模型数据
					this.pageTotal = res.data.data.pageTotal;
					this.recordTotal = res.data.data.recordTotal;
					this.menuList = res.data.data.menuList;

				}).catch(err => { //错误处理
					console.log(err)
				})

			},
			// 删除操作
			handleDelete(index, row) {
				//修改搜索状态，在分页时将调用分页列表方法
				this.searchVisiable = false;
				// 二次确认删除
				this.$confirm('确定要删除吗？', '提示', {
						type: 'warning'
					})
					.then(() => {
						this.tableData.splice(index, 1); //从数据模型中删除
						//发送请求，从数据库中删除数据行row
						axios.delete('/api/article/delete', {
							params: {
								id: row.id //row为一条页面数据
							}
						}).then(res => {
							//console.log(res);
							if (res.data.data) { //为true
								this.$message.success('成功删除1条数据');
							} else {
								this.$message.success('删除数据失败');
							}
						}).catch(err => {
							this.$message.success('删除数据失败');
						})
					})
					.catch(() => {});
			},
			// 多选操作
			handleSelectionChange(val) {
				//console.log(val)
				this.multipleSelection = val;
			},
			//批量删除数据
			delAllSelection() {
				//修改搜索状态，在分页时将调用分页列表方法
				this.searchVisiable = false;
				const length = this.multipleSelection.length;
				//this.delList = this.delList.concat(this.multipleSelection);

				//拼接要删除的数据名称
				for (let i = 0; i < length; i++) {
					//str += this.multipleSelection[i].name + ' ';
					//添加要删除的数据id
					this.delList.push(this.multipleSelection[i].id);
				}
				console.log(this.delList)
				//后端删除对应数据            
				axios.delete('/api/article/deleteAll', {
						data: {
							list: this.delList
						}
					})
					.then(res => {
						console.log(res)
						if (res.data.data) { //为true
							this.$message.success('成功删除数据' + length + '条');
						} else {
							this.$message.success('删除数据失败');
						}
					})
				this.multipleSelection = [];
				//分页查询当前索引页面
				this.handlePageChange(this.query.pageIndex)
			},


			//添加操作
			handleAdd() {
				this.addVisible = true;
			},
			saveAdd() {
				this.getCheckedNodes();
				this.$refs['elForm'].validate(valid => {
					if (!valid) return

					let that = this;
					axios({
						method: 'post',
						url: '/api/article/save',
						data: that.form //提交json格式数据
					}).then(res => { //请求成功时
						//判断json对象为空，Object.keys(res.data.message).length!=0
						console.log(res)
						if (res.data.code == 200) {
							that.$message.success('添加成功');
							that.idx = -1;
							that.form = {}
						} else { //返回空对象时
							console.log(res)
							that.$message.error('添加失败');
						}
					}).catch(err => {
						console.log(err)
						that.$message.error('添加失败！')
					})
					this.addVisible = false;
				})
			},
			// 编辑操作
			handleEdit(index, row) {
				this.idx = index; //编辑数据的索引
				this.form = row;
				this.editVisible = true;
			},
			// 保存编辑
			saveEdit() {
				this.getCheckedNodes();
				if (this.idx > -1) { //编辑数据
					//修改搜索状态，在分页时将调用分页列表方法
					this.searchVisiable = false;
					this.editVisible = false;
					var data = this.form;
					this.interceptor();
					axios.put('/api/article/update', data).then(res => {
						console.log("数据更新成功")
						this.$set(this.tableData, this.idx, this.form);
						this.$message.success(`修改第 ${this.idx + 1} 行成功`);
						this.idx = -1;
						this.form = {}
					}).catch(err => {
						console.log(err)
						this.idx = -1;
						this.form = {}
					})
				} else { //新建
					this.$message.error("编辑失败！");
					this.editVisible = false;
				}
			},

			//预览
			handlePreview(index, row) {
				this.idx = index; //编辑数据的索引
				this.$router.push({
					name: "articleInfo",
					params:{
						id: row.id
					},
				});
			},

			// 分页
			// 分页导航
			handlePageChange(val) { //val为页码索引      	

				if (this.searchVisiable) { //是搜索分页
					this.searchListPages(val)
				} else { //是列表分页
					this.query.pageIndex = val;
					var pageSize = this.query.pageSize;
					//按页码、每页记录数，请求数据
					this.getUserData(val, pageSize);
				}
			},
			// 每页显示的条数
			handleSizeChange(val) {
				// 改变每页显示的条数 
				this.query.pageSize = val
				// 点击每页显示的条数时【10，20】，显示第一页
				this.getUserData(1, val)
				// 注意：在改变每页显示的条数时，要将页码显示到第一页
				this.query.pageIndex = 1
			},
			//添加用户
			addUser() {
				//修改搜索状态，在分页时将调用分页列表方法
				this.searchVisiable = false;
				//状态更新后，调用saveEdit()方法，添加用户
				this.editVisible = true;
				//this.saveEdit();
			},
			//日期格式处理
			dateFormat(row, column, cellValue, index) {
				var date = cellValue
				if (!date) {
					return ''
				}
				return moment(date).format('YYYY年MM月DD日')
			}
		}
	};
</script>

<style scoped>
	.handle-box {
		margin-bottom: 20px;
	}

	.handle-select {
		width: 120px;
	}

	.handle-input {
		width: 300px;
		display: inline-block;
	}

	.table {
		width: 100%;
		font-size: 14px;
	}

	.red {
		color: #ff0000;
	}

	.mr10 {
		margin-right: 10px;
	}

	.table-td-thumb {
		display: block;
		margin: auto;
		width: 40px;
		height: 40px;
	}
</style>
